<template>
  <div class="page">
    <div class="page-panel">
      <!-- start 部门详情 -->
      <div class="page-panel-body">
        <!-- start 操作 -->
        <div>
          <el-tooltip :content="tagDetailData.tagName" placement="top">
            <template v-if="isOpenData && tagDetailData.dingId">
              <open-data type="departmentName" :openid="tagDetailData.dingId"></open-data>
            </template>
            <template v-else>
              <span>{{ tagDetailData.tagName }}</span>
            </template>
          </el-tooltip>
          <div>
            <el-button 
              @click="openDepartmentEditPanel(tagDetailData)"
              v-if="allowTagEdit"
            >
              <i class="iconfont icon-edit-square icon-btn"></i> {{ $t('common.base.edit') }}
            </el-button>

            <el-button
              v-if="!isRootDepartment(tagDetailData) && allowTagDelete"
              @click="delDepartment()"
            >
              <i class="iconfont icon-delete"></i> {{ $t('common.base.delete') }}
            </el-button>
          </div>
        </div>
        <!-- end 操作 -->
      </div>
      <!-- end 部门详情 -->
    </div>

    <div class="page-main">
      <!-- end左侧 -->
      <div class="page-panel page-main-detail" ref="detail">
        <el-tabs :value="activeTab" @input="handleSwitchTab">
          <!-- 详情 -->
          <el-tab-pane :label="$t('common.base.detail')" name="detailInfo">
            <form-view class="task-tab-container task-view-containner" :fields="tagDetailInfo" :value="tagDetailData">
              <!-- 部门主管 -->
              <template slot="teamLeaders">
                <div class="form-view-row">
                  <label>{{ $t('common.label.DepartmentHeads') }}</label>
                  <div class="form-view-row-content">
                    <template v-if="isOpenData">
                      <open-data v-for="item in tagDetailData.teamLeaders" :key="item.staffId" type="userName" :openid="item.staffId"></open-data>
                    </template>
                    <template v-else>
                      {{ teamLeaders }}
                    </template>
                  </div>
                </div>
              </template>

              <!-- 负责区域 -->
              <template slot="tagPlaceList">
                <div class="form-view-row">
                  <label>{{ $t('common.label.territory') }}</label>
                  <div class="form-view-row-content">{{ tagPlaceList }}</div>
                </div>
              </template>

              <!-- 部门位置 -->
              <template slot="tagAddress" slot-scope="{ value }">
                <div class="form-view-row">
                  <label>{{ $t('common.label.departmentLocation') }}</label>
                  <div class="form-view-row-content">
                    <span
                      class="form-view-row-content form-view-row-content-address"
                      v-if="value"
                      @click="openMap"
                    >
                      <i
                        v-if="
                          value.longitude &&
                          value.latitude
                        "
                        class="iconfont icon-address team-address-icon link-text"
                        style="margin: 0"
                      ></i>
                      <el-tooltip
                        :content="value | fmt_address"
                        placement="top"
                      >
                        <span>{{ value | fmt_address }}</span>
                      </el-tooltip>
                    </span>
                  </div>
                </div>
              </template>
            </form-view>
          </el-tab-pane>

          <!-- 子部门 -->
          <el-tab-pane :label="$t('common.label.subDepartment')" name="childTagList">
            <dept-home-child-list
              @childDel="(e) => delDepartment(e)"
              @childEdit="(e) => openDepartmentEditPanel(e)"
              :detailId="detailId"
            ></dept-home-child-list>
          </el-tab-pane>

          <!-- 成员列表 -->
          <el-tab-pane :label="$t('common.label.merberList')" name="userList">
            <dept-user-list :detailId="detailId"></dept-user-list>
          </el-tab-pane>

          <!-- 服务事件 -->
          <el-tab-pane 
            v-if="isShowEventModule"
            :label="$t('common.label.serveEvent')" 
            name="eventsForUserList"
          >
            <dept-events-list :detailId="detailId"></dept-events-list>
          </el-tab-pane>

          <!-- 工单列表 纯客服云版本不显示 -->
          <el-tab-pane v-if="_isShowTaskModule" :label="$t('common.label.taskList')" name="tasksForUserView">
            <dept-tasks-list :detailId="detailId"></dept-tasks-list>
          </el-tab-pane>
        </el-tabs>
      </div>
      <!-- end左侧 -->

      <!-- start 右侧 -->
      <div class="page-panel page-main-addition" ref="addition">
        <div class="page-main-addition-header">{{ $t('common.tabs.recordList') }} </div>
        <!-- 搜索选择 -->
        <dept-records :detailId="detailId"></dept-records>
      </div>
      <!-- end 右侧 -->
    </div>

    <!-- start 编辑 -->
    <base-modal :show.sync="deptDialogVisible" :title="$t('common.base.edit')" @closed="deptDialogVisible = false">
      <team-edit-view
        v-if="deptDialogVisible"
        ref="team"
        @deptSubmit="submitAddDept"
        :selected-dept="tagDetailData"
        :show-parent="false"
        :id="deptEditId"
      ></team-edit-view>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit">{{ $t('common.base.confirm') }}</el-button>
      </span>
    </base-modal>
    <!-- end 编辑 -->
  </div>
</template> 

<script>
import { isOpenData } from '@src/util/platform'
/*global AMap, moment, _init_data*/
import * as DeptHomeApi from "@src/api/DeptHomeApi";
import * as TeamApi from "@src/api/TeamApi";

import _ from "lodash";
import Page from "@src/model/Page";

// components
import TeamEditView from "@src/modules/dept/component/TeamEditView.vue";

import DeptHomeChildList from "./components/DeptHomeChildList.vue";
import DeptEventsList from "./components/DeptEventsList.vue";
import DeptUserList from "./components/DeptUserList.vue";
import DeptTasksList from "./components/DeptTasksList.vue";
import DeptRecords from "./components/DeptRecords.vue";

/* util */
import { getRootWindowInitData } from '@src/util/window'
import { t } from '@src/locales'
/* mixin */
import { 
  VersionControlTaskMixin,
  VersionControlEventMixin
} from '@src/mixins/versionControlMixin'

const rootWindowInitData = getRootWindowInitData()
import { fmtDist } from '@src/util/addressUtil';
export default {
  name: "dept-home-view",
  mixins: [
    VersionControlTaskMixin,
    VersionControlEventMixin
  ],
  components: {
    [TeamEditView.name]: TeamEditView,
    [DeptHomeChildList.name]: DeptHomeChildList,
    [DeptEventsList.name]: DeptEventsList,
    [DeptUserList.name]: DeptUserList,
    [DeptTasksList.name]: DeptTasksList,
    [DeptRecords.name]: DeptRecords,
  },
  data() {
    return {
      isOpenData,
      activeTab: "detailInfo", // 选中的tabs
      pageInfo: {
        // 分页
        pageNum: 1,
        pageSize: 10,
      },
      total: 0, // 总数

      tagDetailData: {}, // 详情数据
      recordsList: [], // 动态
      deptDialogVisible: false,
      deptEditId: "",
      depts: [],
      rootWindowInitData,
    };
  },
  computed: {
    // 详情id
    detailId() {
      return window.location.pathname.split("/security/tag/home/")[1];
    },
    // 详情展示名称
    tagDetailInfo() {
      return [
        { displayName: t('common.label.DepartmentHeads'), fieldName: "teamLeaders", formType:'text', isSystem: 1 },
        { displayName: t('common.label.departmentDesc'), fieldName: "description", formType:'text', isSystem: 1 },
        { displayName: t('common.label.territory'), fieldName: "tagPlaceList", formType:'text', isSystem: 1 },
        { displayName: t('common.label.departmentName'), fieldName: "tagName", formType:'text', isSystem: 1 },
        { displayName: t('common.label.contactMethod'), fieldName: "phone", formType:'text', isSystem: 1 },
        { displayName: t('common.label.departmentLocation'), fieldName: "tagAddress", formType:'text', isSystem: 1 },
      ];
    },
    // 部门主管
    teamLeaders() {
      return (
        this.tagDetailData.teamLeaders &&
        this.tagDetailData.teamLeaders.map((x) => x.displayName).join("，")
      );
    },
    // 负责区域
    tagPlaceList() {
      return this.tagDetailData.tagPlaceList && this.tagDetailData.tagPlaceList
        .map(
          (p) =>
            p &&
            `${fmtDist(p)}`
        )
        .join("，\n");
    },
    // 部门页面的tabid
    parentTab(variable){
      const query = window.location.search.substring(1);
      return query.split('=')[1];
    },
    authorities() {
      return rootWindowInitData?.user?.auth || {}
    },
    allowTagCreate() {
      return this.authorities?.AUTH_TAG
    },
    allowTagEdit() {
      return this.authorities?.TAG_EDIT
    },
    allowTagDelete() {
      return this.authorities?.TAG_DELETE
    },
    isShowEventModule() {
      return this._isShowEventModule
    }
  },
  async mounted() {
    this.depts = await this.fetchDept();

    this.getDeptTagDetail();
  },
  methods: {
    // 部门详情
    getDeptTagDetail() {
      DeptHomeApi.getDeptTagDetail({
        tagId: this.detailId || "",
      }).then((res) => {
        const { status, message, data } = res;
        if (status !== 0) return;

        this.tagDetailData = data;

        const {
          address,
          addressType,
          city,
          dist,
          latitude,
          longitude,
          country,
          province,
        } = data;
        this.tagDetailData.tagAddress = {
          address,
          addressType,
          city,
          dist,
          latitude,
          longitude,
          country,
          province,
        };
      });
    },
    // 切换tabs
    handleSwitchTab() {},
    openMap() {
      this.$fast.map
        .display(this.tagDetailData.tagAddress, { title: t('common.label.departmentLocation') })
        .catch((err) => console.error("openMap catch an err: ", err));
    },
    // 编辑
    openDepartmentEditPanel(row) {
      this.deptEditId = row.id;
      this.deptDialogVisible = true;
    },
    // 编辑提交
    submit() {
      this.$refs.team.submit();
    },
    // 编辑完成
    submitAddDept() {
      this.deptDialogVisible = false;
      this.getDeptTagDetail();

      // 更新服务商页面内容
      this.$platform.refreshTab(this.parentTab);
    },
    /** 抓取部门数据 */
    fetchDept() {
      let params = {
        seeAllOrg: this.isSeeAllOrg,
        keyword: this.deptKeyword,
      };

      return TeamApi.tagV2List(params)
        .then((result) => {
          return (result && result.list) || [];
        })
        .catch((err) => console.error("err", err));
    },
    // 是否展示删除按钮
    isRootDepartment(department = {}) {
      return this.depts.some((dept) => dept.id == department.id);
    },
    // 删除
    async delDepartment(id) {
      // 您删除的团队，如果包含子团队将会一并删除，是否继续？
      try {
        if (
          await this.$platform.confirm(t('common.base.tip.delDepartmentConfirm'))
        ) {
          let ids = [this.tagDetailData.id];
          if (id) ids = [id];

          let result = await TeamApi.deleteTag(ids);

          const state = result.status == 0;
          this.$platform.notification({
            type: state ? "success" : "error",
            title: state ? t('common.base.success') : t('common.base.fail'),
            message: state ? null : result.message,
          });

          if (state) {
            // 更新服务商页面内容
            this.$platform.refreshTab(this.parentTab);

            let id = window.frameElement.dataset.id;
            this.$platform.closeTab(id);
          }
        }
      } catch (e) {
        console.error("teamDelete catch error", e);
      }
    },
  },
};
</script>

<style lang="scss">
.page {
  height: 100%;
  padding: 2px;
}
.service-price-delete {
  float: right;
  color: #f56c6c;
}

.page-panel-body {
  overflow: hidden;
  clear: both;
  > div:first-child {
    display: flex;
    align-items: center;
    justify-content: space-between;
    > span {
      font-size: 16px;
      font-weight: 500;
    }
  }
}

.detail-list-box {
  display: flex;
  flex-direction: column;

  > div {
    padding-right: 64px;
    font-size: 14px;
    display: flex;
    align-items: center;
    margin-bottom: 12px;

    > span {
      width: 130px;
    }

    > p {
      margin: 0;
      flex: 1;
      color: #595959;
      @include text-ellipsis();
    }
  }
}

.page-main {
  min-height: calc(100% - 70px);
}

.page-main-detail {
  overflow: auto;
  flex: 7;
}

.page-main-addition {
  overflow: hidden;
  flex: 3;

  .page-main-addition-header {
    height: 40px;
    line-height: 40px;
    background-color: $bg-color-l2;
    padding: 0 16px;
    border-bottom: 1px solid $color-border-l3;
  }

  .progress-content {
    padding: 16px;
    .page-right-search {
      display: flex;
      flex-direction: column;
      > div {
        display: flex;
        align-items: center;
        margin-bottom: 12px;
        > span {
          min-width: 70px;
        }
        > div {
          flex: 1;
        }
      }
    }
  }
}

.icon-btn {
  vertical-align: middle;
  font-size: 18px;
}

.base-modal-mask {
  z-index: 5000;
}
.amap-sug-result {
  z-index: 5001;
}
</style>

<style lang="scss" scoped>
::v-deep .page-main-detail .el-tabs__nav-scroll {
  padding: 0 16px;
  background-color: $bg-color-l2;
}
::v-deep .page-main-detail .el-tabs__content {
  padding: 1px 16px 16px;
}
::v-deep .el-tabs__nav-wrap::after {
  height: 1px;
}
.page .el-date-editor {
  padding: 0 !important;
}
.form-view-row-content-address {
  cursor: pointer;
}
.form-view-row-content-address:hover {
  color: $color-primary-light-6;
}

::v-deep .el-dialog__wrapper {
  z-index: 3000 !important;
}
</style>